package com.daocao.hua.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.daocao.hua.R;
import com.daocao.hua.adapter.V3AliPayRechargeMoneyAdapter;
import com.daocao.hua.api.callback.RepayInfoContract;
import com.daocao.hua.api.requestInfo.RepayInfoRequest;
import com.daocao.hua.constant.Const;
import com.daocao.hua.constant.UserGlobal;
import com.daocao.hua.event.AlipayUserEvent;
import com.daocao.hua.event.ClosePayActEvent;
import com.daocao.hua.event.OnHomeEventMsg;
import com.daocao.hua.model.AlipayRechargeV3Model;
import com.daocao.hua.model.ConfirmDilaogModel;
import com.daocao.hua.model.PayOrderModel;
import com.daocao.hua.model.PayWayModel;
import com.daocao.hua.model.RechargeModel;
import com.daocao.hua.model.RepayModel;
import com.daocao.hua.model.RepayStatusDialogModel;
import com.daocao.hua.util.ToastUtil;
import com.daocao.hua.util.UI;
import com.daocao.hua.view.Dialog;
import com.daocao.hua.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 2017/9/4.
 */

public class V3AlipayRechargeActivity extends BaseActivity implements RepayInfoContract.View {

    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.list)
    RecyclerView list;
    @BindView(R.id.txt_alipay)
    TextView txtAlipay;
    @BindView(R.id.layout_alipay_account)
    LinearLayout layoutAlipayAccount;
    @BindView(R.id.txt_total)
    TextView txtTotal;
    @BindView(R.id.btn_recharge)
    SuperButton btnRecharge;
    private Unbinder unbinder;
    private RepayInfoRequest api;
    private WebView mWebView;
    private ArrayList<String> explainList;
    private String dealId;
    private String mMoney;
    private float newMoney;
    private String overdue;
    private float balance;
    private float Month_need_all_repay_money;
    private static final String ACTION = "RECHARGE";
    //    private String payment_id;
//    private String selectWays;
    private String notice_sn;
    private String rechargeMoney;
    private V3AliPayRechargeMoneyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recharge_alipay_v3);
        initBar();
        unbinder = ButterKnife.bind(this);

        txtTitle.setText("充值");
        api = RepayInfoRequest.create();
        api.attachView(this);

        String alipay = getIntent().getStringExtra("alipay");
        if (TextUtils.isEmpty(alipay)) {
            alipay = "";
        }
        txtAlipay.setText(alipay);
        EventBus.getDefault().register(this);

        api.getRepayInfo();


        init();
    }


    private void init() {
//        payment_id = getIntent().getStringExtra("payment_id");
//        selectWays = getIntent().getStringExtra("selectWays");
//
//        if (TextUtils.isEmpty(payment_id)) {
//            api.getPayWay();
//        }
        txtAlipay.setText(UserGlobal.getAlipay());
        mWebView = new WebView(getApplicationContext());
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebChromeClient(new WebChromeClient());

        adapter = new V3AliPayRechargeMoneyAdapter(this);
        adapter.setOnChooseListener(new V3AliPayRechargeMoneyAdapter.OnChooseListener() {
            @Override
            public void onClick(String money) {
                rechargeMoney = money;
                txtTotal.setText("共计" + money + "元");
            }
        });
        list.setLayoutManager(new GridLayoutManager(this, 2));
        list.setAdapter(adapter);

        List<String> data = new ArrayList<>();
        data.add("300");
        data.add("200");
        data.add("100");
        data.add("0");
        adapter.update(data);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAlipayUser(AlipayUserEvent msg) {
        txtAlipay.setText(msg.user);
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (isGotoPay) {
            isGotoPay = false;
            api.getRepayDialog();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            mWebView.onPause();
            mWebView.destroy();
            mWebView = null;
        }

        EventBus.getDefault().unregister(this);
        api.detachView();
        api = null;
        unbinder.unbind();
        unbinder = null;
    }

    @Override
    public void showError() {

    }

    @Override
    public void complete() {
        loadingDialog.dismiss();
    }

    @Override
    public void onRequestStart() {
        loadingDialog.show();
    }

    @Override
    public void getRepayInfoSuccess(RepayModel item) {

        dealId = item.getData().getId();
        Month_need_all_repay_money = item.getData().getMonth_need_all_repay_money();
        balance = item.getData().getUser_balance();
        mMoney = item.getData().getNeed_repay_money_format();

        if (!TextUtils.isEmpty(mMoney)) {
            if (mMoney.contains("￥")) mMoney = mMoney.replace("￥", "");
            if (mMoney.contains(",")) mMoney = mMoney.replace(",", "");
        }


        overdue = item.getData().getImpose_all_money_format();
//        已逾期XX天   待还金额XX元
//        if (item.getData().getImpose_day() == 0) {
//            UI.setTvHtml(txtTips, R.string.recharge_money_tips_noimpose, "近日待还金额", "￥" + item.getData().getMonth_need_all_repay_money());
//        } else {
//            UI.setTvHtml(txtTips, R.string.recharge_money_tips, "已逾期", item.getData().getImpose_day(), "天&#160;&#160;待还金额", item.getData().getMonth_need_all_repay_money(), "元");
//        }
        if (TextUtils.isEmpty(mMoney)) {
            return;
        }
        if (item.getData().getUser_balance() != 0)
            newMoney = Float.parseFloat(mMoney) - item.getData().getUser_balance();
        else
            newMoney = Float.parseFloat(mMoney);
    }

    @Override
    public void getRechargeTipsSuccess(AlipayRechargeV3Model item) {
        String url = item.data.alipay_money_links;
//        "go_alipay": 1   // 是否直接调整至支付宝：0 - 否，1 - 是
        isGotoPay = true;
        if (item.data.go_alipay.equals("1")) {
            if (!checkAliPayInstalled(this)) {
                mWebView.loadUrl(url);
                return;
            }
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse(Const.ALIPAY_START + url + Const.ALIPAY_END);
            intent.setData(content_url);
            startActivity(intent);
        } else if (item.data.go_alipay.equals("0")) {
            mWebView.loadUrl(url);
        }
    }

    @Override
    public void getRepayDialogSuccess(RepayStatusDialogModel item) {
//        "is_alerts": 1,  //是否需要弹窗：0 - 否，1 - 是
        //订单状态：0 - 待确认、 1 - 失败、 2 - 成功、4 - 无订单
        explainList = item.data.explain;

        if (item.data.order_status == 2) {
            Map<String, String> map = new HashMap<>();
            map.put("type", Const.SendType.UPDATE_REPAY);
            EventBus.getDefault().post(new OnHomeEventMsg(map));
            ToastUtil.makeText(this, "支付成功").show();
            finish();
        } else if (item.data.order_status == 1) {
            ToastUtil.makeText(this, "支付失败").show();
        } else if (item.data.order_status == 4) {
            ToastUtil.makeText(this, "支付失败").show();
        } else if (item.data.order_status == 0) {
            notice_sn = item.data.notice_sn;
            if (item.data.is_alerts == 0) {
            } else if (item.data.is_alerts == 1) {
                Dialog.showConfirmDialog(this, new Dialog.DialogDefaultClickListener() {
                    //                确认支付成功
                    @Override
                    public void confirm() {
                        api.confirmDialog(item.data.notice_id, api.SUCCESS);
                    }

                    //                点击支付失败
                    @Override
                    public void cancel() {
                        Dialog.showDefaultDialog(V3AlipayRechargeActivity.this, "提示", "确定支付失败吗？", "确定", "返回", false, new Dialog.DialogDefaultClickListener() {
                            @Override
                            public void confirm() {
//                            点击返回，显示上一个Dialog;
                                Dialog.showConfirmDialog(V3AlipayRechargeActivity.this, new Dialog.DialogDefaultClickListener() {
                                    @Override
                                    public void confirm() {
                                        api.confirmDialog(item.data.notice_id, api.SUCCESS);
                                    }

                                    @Override
                                    public void cancel() {
                                        Dialog.showDefaultDialog(V3AlipayRechargeActivity.this, "提示", "确定支付失败吗？", "确定", "返回", false, new Dialog.DialogDefaultClickListener() {
                                            @Override
                                            public void confirm() {

                                            }

                                            @Override
                                            public void cancel() {
                                                api.confirmDialog(item.data.notice_id, api.FAILED);
                                            }
                                        });
                                    }
                                });
                            }

                            @Override
                            public void cancel() {
                                //                            点击确认，支付失败;
                                api.confirmDialog(item.data.notice_id, api.FAILED);
                            }
                        });
                    }
                });
            }
        }
    }

    private boolean isGotoPay = false;

    @Override
    public void confirmDialogSuccess(ConfirmDilaogModel item, String confirm) {
        if (confirm.equals(api.FAILED)) {
//            finish();
        } else if (confirm.equals(api.SUCCESS)) {
            gotoShenhe(explainList);
        }
    }

    @Override
    public void getPayWaySuccess(PayWayModel item) {
//        selectWays = item.data.get(0).payment_class_name;
//        payment_id = item.data.get(0).payment_id + "";
    }


    @Override
    public void getPayOrderSuccess(PayOrderModel data) {
        String url = data.data.alipay_money_links;
//        "go_alipay": 1   // 是否直接调整至支付宝：0 - 否，1 - 是
        isGotoPay = true;
        if (data.data.go_alipay.equals("1")) {
            if (!checkAliPayInstalled(this)) {
                mWebView.loadUrl(data.data.alipay_money_links);
                return;
            }
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse(Const.ALIPAY_START + data.data.alipay_money_links + Const.ALIPAY_END);
            intent.setData(content_url);
            startActivity(intent);
        } else if (data.data.go_alipay.equals("0")) {
            mWebView.loadUrl(url);
        }
    }

    private void gotoShenhe(ArrayList<String> explain) {
//        if (TextUtils.isEmpty(dealId)) {
//            api.getRepayInfo();
//            return;
//        }
        EventBus.getDefault().post(new ClosePayActEvent());
        Intent intent = new Intent(this, ShenHeActivity.class);
        intent.putExtra("deal_id", dealId);
        intent.putExtra("money", newMoney + "");
        intent.putExtra("overdue", overdue);
        intent.putExtra("order", notice_sn);
        intent.putExtra("total_money", (int) Month_need_all_repay_money);
        intent.putExtra("balance", balance);
        intent.putExtra("isRecharge", true);
        intent.putStringArrayListExtra("explain", explain);
        startActivity(intent);
        overridePendingTransition(R.anim.right_enter, R.anim.left_out);
        finish();
    }

    private boolean checkAliPayInstalled(Context context) {
        Uri uri = Uri.parse("alipays://platformapi/startApp");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        ComponentName componentName = intent.resolveActivity(context.getPackageManager());
        return componentName != null;
    }

    @OnClick({R.id.btn_back, R.id.btn_recharge, R.id.layout_alipay_account})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_recharge:
                if (TextUtils.isEmpty(rechargeMoney)) {
                    ToastUtil.makeText(this, "充值金额不能为空").show();
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(txtAlipay))) {
                    ToastUtil.makeText(this, "请选择支付宝账号").show();
                    return;
                }
//                if (TextUtils.isEmpty(payment_id)) {
//                    api.getPayWay();
//                    return;
//                }

                api.getRechargeTips(rechargeMoney, UI.toString(txtAlipay));
//                api.getPayOrder(ACTION, payment_id, selectWays, rechargeMoney, UI.toString(txtAlipay));
                break;
            case R.id.layout_alipay_account:
                Intent intent = new Intent(this, V3AlipayAddActivity.class);
                intent.putExtra("alipay", UI.toString(txtAlipay));
                startActivity(intent);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
        }
    }
}
